package com.central.common.handler;

import cn.hutool.json.JSONUtil;
import com.central.common.entity.*;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Tindy
 * @date 2022/1/14
 * @describe
 */
@MappedJdbcTypes(JdbcType.VARCHAR)  // 数据库类型
@MappedTypes({TaskContent.class})          // java数据类型
public class TaskContentToStringHandler extends BaseTypeHandler<TaskContent> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, TaskContent taskContent, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSONUtil.toJsonStr(taskContent));
    }

    @Override
    public TaskContent getNullableResult(ResultSet resultSet, String s) throws SQLException {
        TaskContent taskContent=null;
        switch (resultSet.getString("task_type")){
            case "SHELL":
                taskContent = JSONUtil.toBean(resultSet.getString(s), ShellTaskContent.class);
                break;
            case "SQL":
                taskContent = JSONUtil.toBean(resultSet.getString(s), SqlTaskContent.class);
                break;
            case "DATAX":
                taskContent = JSONUtil.toBean(resultSet.getString(s), DataxTaskContent.class);
                break;
            case "FLINK_SQL":
                taskContent = JSONUtil.toBean(resultSet.getString(s), FlinkSqlTaskContent.class);
                break;
            default:
                break;
        }
        return taskContent;
    }

    @Override
    public TaskContent getNullableResult(ResultSet resultSet, int i) throws SQLException {
        TaskContent taskContent=null;
        switch (resultSet.getString("task_type")){
            case "SHELL":
                taskContent = JSONUtil.toBean(resultSet.getString(i), ShellTaskContent.class);
                break;
            case "SQL":
                taskContent = JSONUtil.toBean(resultSet.getString(i), SqlTaskContent.class);
                break;
            default:
                break;
        }
        return taskContent;
    }

    @Override
    public TaskContent getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        TaskContent taskContent=null;
        switch (callableStatement.getString("task_type")){
            case "SHELL":
                taskContent = JSONUtil.toBean(callableStatement.getString(i), ShellTaskContent.class);
                break;
            case "SQL":
                taskContent = JSONUtil.toBean(callableStatement.getString(i), SqlTaskContent.class);
                break;
            default:
                break;
        }
        return taskContent;
    }
}

